package cn.ibizlab.odoo.mob.rt.service;

import lombok.extern.slf4j.Slf4j;

import cn.ibizlab.odoo.util.feign.FeignRequestInterceptor;
import cn.ibizlab.odoo.util.feign.suport.SearchContextFeignEncode;
import cn.ibizlab.odoo.mob.MobApplication;
import cn.ibizlab.odoo.mob.rt.domain.SRFFILE;
import cn.ibizlab.odoo.mob.rt.feign.SRFFileFeignClient;
import feign.Client;
import feign.Contract;
import feign.Feign;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.stereotype.Component;
import cn.ibizlab.odoo.util.log.IBIZLog;

/**
 * 文件上传
 */
@Slf4j
@IBIZLog
@Component
public class SRFFileService {

    SRFFileFeignClient client;

    @Autowired
    public SRFFileService(Decoder decoder, Encoder encoder, Client client, Contract contract, FeignRequestInterceptor feignRequestInterceptor,
        MobApplication.WebClientProperties webClientProperties) {
        if (webClientProperties.getServiceId()!=null) {
            Feign.Builder nameBuilder = Feign.builder()
                    .client(client)
                    .encoder(new SearchContextFeignEncode(encoder))
                    .decoder(decoder)
                    .contract(contract)
                    .requestInterceptor(feignRequestInterceptor)
                    ;
            this.client = nameBuilder.target(SRFFileFeignClient.class,"http://" + webClientProperties.getServiceId() + "/") ;
        } else if (webClientProperties.getServiceUrl()!=null) {
            if (client instanceof LoadBalancerFeignClient) {
                client = ((LoadBalancerFeignClient) client).getDelegate();
            }
            Feign.Builder nameBuilder = Feign.builder()
                    .client(client)
                    .encoder(new SearchContextFeignEncode(encoder))
                    .decoder(decoder)
                    .contract(contract)
                    .requestInterceptor(feignRequestInterceptor)
                    ;
            this.client = nameBuilder.target(SRFFileFeignClient.class, "http://" + webClientProperties.getServiceUrl() + "/") ;
        }
    }

    /**
     * 保存file记录
     * @param fileId
     * @param ibzfile
     * @return
     */
    public boolean save(String fileId, SRFFILE ibzfile) {
        return client.save(fileId, ibzfile);
    }

    /**
     * 获取file记录
     * @param fileId
     * @return
     */
    public SRFFILE get(String fileId) {
        return client.get(fileId);
    }

}
